/*
 * Licensed Materials - Property of tenxcloud.com
 * (C) Copyright 2018 TenxCloud. All Rights Reserved.
 * 2018-06-13  @author lizhen
 */

package project

import "github.com/jinzhu/gorm"

type count struct {
	Count int `gorm:"column:count"`
}

func UserBelongsToProject(userID int, project string, db *gorm.DB) (bool, error) {
	var c count
	if err := db.Raw(`SELECT count(tenx_project_user.id) AS count
  FROM tenx_project
  JOIN tenx_project_user ON tenx_project.id = tenx_project_user.project_id
    WHERE tenx_project_user.user_id = ?
      AND tenx_project.name = ?`, userID, project).Scan(&c).Error; err != nil {
		return false, err
	}
	return c.Count > 0, nil
}

func IsUserProjectAdmin(userID int, projectNamespace string, db *gorm.DB) (bool, error) {
	var c count
	if err := db.Raw(`SELECT COUNT(tenx_user_role.id) AS count
FROM tenx_project
       INNER JOIN tenx_user_role ON tenx_project.id = tenx_user_role.scope_id
WHERE tenx_user_role.scope = 200
  AND tenx_project.namespace = ?
  AND tenx_user_role.user_id = ?`, userID, projectNamespace).Scan(&c).Error; err != nil {
		return false, err
	}
	return c.Count > 0, nil
}
